package com.wawayaya.bookreader.speedregulation;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.wawayaya.bookreader.DefaultSettings;
import com.wawayaya.bookreader.jni.Audio2Wav;
import com.wawayaya.util.TLog;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;


/**
 * 语速 管理 thread
 * Created by wang_qian on 2015/6/27.
 */
public class SpeedRegulationThread extends Thread {

    private ArrayList<SpeedConvertItem> mConvertList = new ArrayList<SpeedConvertItem>();
    private AtomicBoolean mStopThread = new AtomicBoolean(false);
    private Handler mHandler;
    private Context mContext;

    public SpeedRegulationThread(Context context, Handler handler) {
        mContext = context;
        mHandler = handler;
        mStopThread.set(false);
    }

    public synchronized SpeedConvertItem getSpeedConvertItemByIndex(int index) {
        if (index >= 0 && index < mConvertList.size()) {
            return mConvertList.get(index);
        }
        return null;
    }

    public synchronized  void addSpeedConvertItem(SpeedConvertItem item) {
        if (!mConvertList.contains(item)) {
            TLog.log("convert addSpeedConvertItem really " + item.mSoundFilePath + " speed = " + item.mSpeed);
            mConvertList.add(item);
            TLog.log("convert mConvertList.notify()");
            if (mConvertList.size() == 1) {
                synchronized (mConvertList) {
                    mConvertList.notify();
                }
            }
            TLog.log("convert mConvertList.notify() end");
        }
    }

    public synchronized void removeSpeedConvertItem(SpeedConvertItem item) {
        mConvertList.remove(item);
    }

    public synchronized void removeSpeedConvertItemByPageIndex(int pageindex) {

        for (SpeedConvertItem item : mConvertList) {
            if (item.mPageIndex == pageindex) {
                mConvertList.remove(item);
            }
        }
    }

    @Override
    public void run() {
        while(!mStopThread.get()) {
            SpeedConvertItem currentobj = null;
            synchronized (mConvertList) {
                if (mConvertList.isEmpty()) {
                    try {
                        TLog.log("convert mConvertList.wait()");
                        mConvertList.wait();
                        TLog.log("convert mConvertList.wait() end");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

            currentobj = getSpeedConvertItemByIndex(0);
            if (currentobj != null && !mStopThread.get()) {
                if (!convertNow(currentobj)){
                    TLog.log("convert " + currentobj.mSoundFilePath + " error!");
                    removeSpeedConvertItemByPageIndex(currentobj.mPageIndex);
                } else {
                    if (currentobj.mIndex == currentobj.mTotalFileNumber - 1 && currentobj.mSpeed == DefaultSettings.SPEED_SLOW) {
                        Message msg = mHandler.obtainMessage(0, currentobj.mPageIndex, currentobj.mBookId, currentobj.mSoundFilePath );
                        mHandler.sendMessage(msg);
                    }
                    removeSpeedConvertItem(currentobj);
                }
            }
            if (!mStopThread.get()) {
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }



    public void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ( (byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                   // System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean  convertNow(SpeedConvertItem item) {
        File file = new File(item.mSoundFilePath);
        TLog.log("convert " + item.mSoundFilePath + " speed = " + item.mSpeed);
        if (file != null && file.exists() && file.isFile()) {
            String parentpath = file.getParent();
            String filename = file.getName();
            File tempfile = null;
            String tempfilepath = null;
            String datafilepath = "";
            String tempdatafilepath = "";
            if (item.mSpeed == DefaultSettings.SPEED_FAST) {
                tempfilepath = parentpath + File.separator + filename.substring(0, filename.length() - 2) + "_fast.wav";

                datafilepath = mContext.getFilesDir() + File.separator + filename + "p3";
                tempdatafilepath = mContext.getFilesDir() + File.separator + filename.substring(0, filename.length() - 2) + "_fast.wav";
                copyFile(item.mSoundFilePath, datafilepath);

                Log.e("SpeedRegulationThread", "SpeedRegulationThread.....tempdatafilepath:" + tempdatafilepath + " tempfilepath:" + tempfilepath);

                //Audio2Wav.Convert(item.mSoundFilePath, tempfilepath, 50, 0, 0, Audio2Wav.CONVERT_OPTION_SPEECH);
                Audio2Wav.Convert(datafilepath, tempdatafilepath, 50, 0, 0, Audio2Wav.CONVERT_OPTION_SPEECH);
                copyFile(tempdatafilepath, tempfilepath);
            } else {
                tempfilepath = parentpath + File.separator + filename.substring(0, filename.length() - 2) + "_slow.wav";

                datafilepath = mContext.getFilesDir() + File.separator + filename + "p3";
                tempdatafilepath = mContext.getFilesDir() + File.separator + filename.substring(0, filename.length() - 2) + "_slow.wav";
                copyFile(item.mSoundFilePath, datafilepath);

                //Audio2Wav.Convert(item.mSoundFilePath, tempfilepath, -25, 0, 0, Audio2Wav.CONVERT_OPTION_SPEECH);
                Audio2Wav.Convert(datafilepath, tempdatafilepath, -25, 0, 0, Audio2Wav.CONVERT_OPTION_SPEECH);
                copyFile(tempdatafilepath, tempfilepath);

            }
            tempfile = new File(datafilepath);
            if (tempfile != null && tempfile.exists()) {
                tempfile.delete();
            }

            tempfile = new File(tempdatafilepath);
            if (tempfile != null && tempfile.exists()) {
                tempfile.delete();
            }




            TLog.log("convert success " + item.mSoundFilePath + " speed = " + item.mSpeed);
            return  true;
        } else {
            TLog.log("convert fail " + item.mSoundFilePath + " speed = " + item.mSpeed);
            return false;
        }
    }

    public void stopThread() {

        mStopThread.set(true);

        synchronized (mConvertList) {
            if (mConvertList.isEmpty())  mConvertList.notify();
        }
    }

    public synchronized void clearList() {
        mConvertList.clear();


    }

}
